import { _decorator, Component, EventTouch, NodeEventType, Node, instantiate, Animation, UITransform, EventTarget, view, AudioSource, sys } from 'cc';
const { ccclass } = _decorator;

export const InputEventTarget = new EventTarget();
@ccclass('TouchManager')
export class TouchManager extends Component {
    public static Instance: TouchManager;

    /**点击特效对象池 */
    private pool: Node;

    protected onLoad(): void {
        TouchManager.Instance = this;
    }

    start() {
        let is_show: boolean = true;
        let transform = this.node.getComponent(UITransform);
        let offset = transform.width / view.getViewportRect().width;
        if (screen.height / screen.width < 1200 / 720) {
            is_show = false;
        }
        this.pool = this.node.getChildByName("pool");

        this.node.on(NodeEventType.TOUCH_START, (evt) => {
            evt.preventSwallow = true;
            InputEventTarget.emit(NodeEventType.TOUCH_START, evt);
        }, this, false)

        this.node.on(NodeEventType.TOUCH_MOVE, (evt) => {
            evt.preventSwallow = true;
            InputEventTarget.emit(NodeEventType.TOUCH_MOVE, evt);
        }, this, false)

        this.node.on(NodeEventType.TOUCH_END, (evt: EventTouch) => {
            InputEventTarget.emit(NodeEventType.TOUCH_END, evt);
            evt.preventSwallow = true
            if (is_show) {
                let tap: Node = null;
                if (this.pool.children.length > 1) {
                    tap = this.pool.children[1];
                } else {
                    tap = instantiate(this.pool.children[0]);
                }
                tap.setParent(this.node);
                tap.getComponent(Animation).play();
                tap.setPosition(evt.getLocationX() * offset, evt.getLocationY() * offset);
                this.scheduleOnce(() => {
                    tap.setParent(this.pool);
                }, 0.5);
            }
        }, this, false)
    }
}